import { Form, Input, Button, Checkbox, message, Popover } from 'antd';
import { saveAs } from 'file-saver';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { connect, history, useDispatch } from 'umi';

import type { Dispatch } from 'umi';

import Andon from '@/assets/images/Andon.svg';
import { calculateOrderAmount, getAllDocx } from '@/services/orderManage';
import { getErrorMsg, priceFormat } from '@/util/utils';

import styles from './index.less';

export interface Props {
  currentOrder: any;
}

const pattern = /^\+?[0-9]\d*$/;
const USER_INFO = JSON.parse(localStorage.getItem('USER_INFO') as string);
const PurchasedProducts = JSON.parse(localStorage.getItem('PurchasedProducts') as string);
export const PRODCTION_NAME = '芍园云安灯软件服务-';
const AddProductionLineUserNum = (props: Props) => {
  const [form] = Form.useForm();
  const [checked, setChecked] = useState<boolean>(false);
  const [buttonLoading, setButtonLoading] = useState<boolean>(false);
  const [addedProductionLine, setAddedProductionLine] = useState(0);

  const [list, setList] = useState<any>(null);
  const [getPrice, setGetPrice] = useState(0);
  const dispatch = useDispatch<Dispatch>();
  function handleOnchange(e: any) {
    console.log(`checked = ${e.target.checked}`);
    setChecked(e.target.checked);
  }

  const getTotalPrice = useMemo(() => {
    return (getPrice);
  }, [getPrice, addedProductionLine]);

  const getList = async () => {
    if (PurchasedProducts) {
      setList(PurchasedProducts);
      form.setFieldsValue({
        orderType: PRODCTION_NAME + PurchasedProducts.productName,
        companyName: USER_INFO?.companyName,
        phone: USER_INFO?.mobileNo,
        productionLineNum: PurchasedProducts.buyedProductionLineNumber,
        price: PurchasedProducts.price,
      });
    }
  };

  useEffect(() => {
    // localStorage.removeItem('CURRENT_ORDER_INFO');
    console.log(props);
    getList();
  }, [PurchasedProducts]);

  const handleAddProductionLine = async (e: any) => {
    const productionLineNum = form.getFieldValue('productionLineNum');
    const value = Number(e.target.value) + Number(productionLineNum);
    if (e.target.value === '') {
      return;
    }
    if (!pattern.test(e.target.value)) {
      form.setFieldsValue({
        addProductionLine: 1,
      });
      return message.warn('必须输入大于零的正整数');
    }
    if (value>=1 && value<=20) {
      form.setFieldsValue({
        price: 1980,
      });
    } else if (value>=21 && value<=30) {
      form.setFieldsValue({
        price: 1728,
      });
    } else if (value>=31 && value<=40) {
      form.setFieldsValue({
        price: 1584,
      });
    } else if (value>=41 && value<=50) {
      form.setFieldsValue({
        price: 1386,
      });
    } else if (value>=51 && value<=60) {
      form.setFieldsValue({
        price: 1188,
      });
    } else if (value>60) {
      form.setFieldsValue({
        price: 990,
      });
    }
    setAddedProductionLine(e.target.value);
    const formData = form.getFieldsValue();
    const createOrderParams = {
      orderType: 5,
      saasProductId: list?.productId,
      unitPrice: Number(formData.price),
      discount: 0,
      buyTimes: null,
      buyedProductionLineNumber: Number(formData.addProductionLine),
      buyUserId: '',
      buyTimeUnit: 3,
    };
    const res = await calculateOrderAmount(createOrderParams);
    if (res.code===200) {
      setGetPrice(res.data.data);
    } else {
      message.error(getErrorMsg(res));
    }
  };

  const handleEnter = useCallback(() => {
    form.validateFields().then(() => {
      setButtonLoading(true);
      const formData = form.getFieldsValue();
      if (formData.addProductionLine<=0) {
        return message.warn('产线数量应该大于0！');
      }
      const createOrderParams = {
        orderType: 5,
        saasProductId: list?.productId,
        unitPrice: Number(formData.price),
        discount: 0,
        // paymentAmount: getTotalPrice,
        paymentAmount: null,
        buyTimes: null,
        buyedProductionLineNumber: Number(formData.addProductionLine),
        buyUserId: '',
        buyTimeUnit: 3,
        companyName: formData.companyName,
        contactNo: formData.phone,
      };
      dispatch({
        type: 'OrderManage/add',
        payload: createOrderParams,
        callback: (res: any) => {
          if (res.code == 200) {
            // localStorage.setItem('CURRENT_ORDER_ID', res.data.data);
            const formValues = {
              id: res.data.data,
              ...formData,
            };
            localStorage.setItem('CURRENT_ORDER_INFO', JSON.stringify({
              ...formValues,
              totalPrice: getTotalPrice,
              addProduction: true,
              totalLine: Number(form.getFieldValue('addProductionLine')),
              // totalLine: Number(form.getFieldValue('addProductionLine')) + Number(formData?.productionLineNum),
            }));
            setButtonLoading(false);
            window.open('/OrderPay');
          } else {
            message.error(getErrorMsg(res));
            setButtonLoading(false);
          }
        },
      });
      // history.push('OrderPay');

    });

  }, [dispatch, form, getTotalPrice, list?.productId]);

  return (
    <>
      <div className={styles.orderPayContent} style={{ background: 'rgb(248, 249, 252)' }}>
        <div className={styles.logo} onClick={() => history.push('/')}>
          <div>
            <img src={Andon} alt="" />{' '}
          </div>
          <div>
            <div className={styles.andon}>Andon</div>
            <div className={styles.sys}>异常快速反应系统</div>
          </div>
        </div>
        <div className={styles.card} style={{ background: 'rgb(248, 249, 252)' }}>
          <div className={styles.content}>
            <div onClick={() => history.push('/')} className={styles.title}>产品服务订单-新增产线</div>
            <div style={{ margin: '0 auto', width: '50%', padding: '0 40px' }}>
              <Form
                form={form}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 19 }}
                initialValues={{}}
                autoComplete="off"
              >
                <Form.Item label="订购版本" name="orderType">
                  <Input disabled={true} />
                </Form.Item>
                <Form.Item label="价格" name="price">
                  <Input disabled={true} />
                </Form.Item>
                <Form.Item label="企业全称" name="companyName" >
                  <Input disabled={true} />
                </Form.Item>
                <Form.Item label="联系电话" name="phone"
                  rules={[
                    { required: true, message: '请输入联系电话!' },
                    { pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/, message: '请输入正确的手机号' },
                  ]}
                >
                  <Input  />
                </Form.Item>
                <Form.Item label="当前产线" name="productionLineNum">
                  <Input disabled={true} />
                </Form.Item>
                <Form.Item
                  label="新增产线"
                  name="addProductionLine"
                  rules={[{ required: true, message: '请输入产线数量!' }]}
                  getValueFromEvent={(e: any) => {
                    const { value } = e.target;
                    return value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g, '');
                  }}
                >
                  <Input placeholder={'请输入产线数量'} onChange={handleAddProductionLine} />
                </Form.Item>
              </Form>
            </div>

          </div>
          <div className={styles.bottomContent}>
            <div className={styles.math}>
              {/*199元 ÷ 365天 × 1人 (新增用户) × 0产线 (新增产线) × 94天 (剩余天数)*/}
            </div>
            <div className={styles.orderMoney}>
              订单金额 <span>￥{priceFormat((getTotalPrice))}</span>
            </div>
            <div className={styles.des}>提交订单后可申请合同、开具发票</div>
            <div className={styles.agreeAndButton}>
              <Checkbox onChange={handleOnchange} />
              &nbsp; &nbsp;同意&nbsp; &nbsp;
              <Popover content={(<div style={{ cursor: 'pointer', color: '#1a3dc9' }} onClick={ async () => {
                const res = await getAllDocx(2);
                if (res.code===200) {
                  const fileType = (res.data.path).split('.')[1];
                  saveAs('images/' + res.data.path, `芍园云软件付费服务协议.${fileType}`);
                } else {
                  message.error('下载错误！');
                }
              }}>芍园云软件付费服务协议</div>)} title="下载条款">
                <span className={styles.safe} onClick={() => window.open('Agreement?id=2')}>芍园云软件付费服务协议</span>
              </Popover>
              <Button loading={buttonLoading} type={'primary'} disabled={!checked} onClick={() => handleEnter()}>
                提交订单
              </Button>
            </div>
          </div>
        </div>
      </div>
    </>

  );
};
const mapState = (state: any) => {
  return {
    currentOrder: state.OrderManage.currentOrder,
  };
};
export default connect(mapState)(AddProductionLineUserNum);
